#include <gtk/gtk.h>
#include "file_address.h"
#include "widgets.h"
#include "password_generator.h"

gint generate_from_file(GtkWidget * caller, gpointer data) 
{
	// Check for file address
	if (file_address[0] == 0)
	{
		gtk_text_buffer_set_text(output_buffer, "No file specified", -1);
		return 1;
	}
	// Open file
	FILE * accounts_csv = fopen(file_address, "r");
	if (accounts_csv == NULL)
	{
		gchar * output_text = g_strdup_printf("Failed to open: %s", file_address);
		gtk_text_buffer_set_text(output_buffer, output_text, -1);
		g_free(output_text);
		return 1;
	}
	// Check keyword for input
    const gchar * keyword = gtk_entry_get_text(GTK_ENTRY(keyword_entry_0));
	if (keyword[0] == 0)
	{
		gtk_entry_set_placeholder_text(GTK_ENTRY(keyword_entry_0), "Keyword required");
		return -3;
	}
	gtk_entry_set_placeholder_text(GTK_ENTRY(keyword_entry_0), "Keyword");
	// Iterate over each line in accounts_csv, generate password and write to output

	gchar line_buffer[1024], service_buffer[1024], username_buffer[1024];
	gint length, special;
	
	gtk_text_buffer_set_text(output_buffer, "", -1);
	while ( fgets(line_buffer, 1024, accounts_csv) )
	{
		if ( sscanf(line_buffer, "%[^,],%[^,],%d,%d", service_buffer, username_buffer, &length, &special) != 4)
		{
			continue;
		}

		char password[length + 1];
		generate_password(password, keyword, service_buffer, username_buffer, length, special);

		char * output_text = g_strdup_printf("/--------------------------------%s\n%s\n%s\n\n", 
				service_buffer,
				username_buffer,
				password);
		GtkTextIter end;
		gtk_text_buffer_get_end_iter(output_buffer, &end);
		gtk_text_buffer_insert(output_buffer, &end, output_text, -1);
		g_free(output_text);
	}
	fclose(accounts_csv);    
}

